package utils;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Hero on 2015/8/7.
 */
public class FileUtils {
    /**
     * 閬嶅巻鏂囦欢澶瑰強鍚勭骇瀛愭枃浠跺す鎵惧嚭鎵�湁鏂囦欢
     * @param dir 蹇呴』鏄枃浠跺す
     * @return 鎵�湁鎵惧埌鐨勬枃浠�
     */
    public ArrayList<File> getAllSubFiles(File dir){
        if (dir.isFile())return  null;
        ArrayList<File> lf=new ArrayList<>();
        File[] files=dir.listFiles();
        for (File f:files){
            if (f.isDirectory()){
               List<File> l= getAllSubFiles(f);
                if (l!=null)lf.addAll(l);
            }
                else if (f.isFile())
                lf.add(f);
        }

     return lf;

    }

    public int getAllSubFileCount(File file){
        if (file.isFile())return 0;

        File[] files=file.listFiles();

        int result=0;
        for(int i=0;i<files.length;i++){
            if (files[i].isFile()) result++;
            else if (files[i].isDirectory())
               result+= getAllSubFileCount(files[i]);

        }
        return result;
    }
    public void deleteDir(File file){
        if (!file.isDirectory())return;
        File[] files=file.listFiles();
        for (File f:files){
            if (f.isFile())f.delete();
            else{
                deleteDir(f);
            }
        }
        file.delete();
    }

    /**
     * 閲嶅懡鍚�锛屽鏋滄枃浠跺凡缁忓瓨鍦紝灏变細鍦ㄥ悗闈㈠姞涓婏紙1锛夛紝锛�锛夌洿鍒板彲浠ュ垱寤烘枃浠躲�
     * @param oldFile  瑕侀噸鍛藉悕鐨勬枃浠躲�
     * @param newFile  瑕侀噸鍛藉悕鎴愮殑鏂囦欢銆�
     * @return 鏈�粓鐨勭粨鏋�
     */
    public   File renameFile(File oldFile,File newFile){
        if (oldFile.getPath().equals(newFile.getPath()))
            return oldFile;
        File file=new File(newFile.getPath());
        for (int i=1;file.exists();i++){
            file=new File(newFile.getPath()+
                    '('+i+')');
        }
        boolean b=oldFile.renameTo(file);
        return file;

    }

    /**
     * 瀹夊叏鍦板垱寤烘枃浠躲�
	 * 濡傛灉file鐨勮矾寰勪笉姝ｇ‘锛堟瘮濡備竴涓埗鏂囦欢澶圭殑鍚嶅瓧琚竴涓枃浠跺崰鏈夛級锛屽彲鑳芥棤娉曞垱寤烘枃浠讹紝杩斿洖null銆�
     * @param file 瑕佸垱寤虹殑鏂囦欢
     * @param cover 濡傛灉涓篺alse锛屽嵆涓嶈鐩栧凡缁忓瓨鍦ㄧ殑鏂囦欢锛岄偅涔堝氨浼氬湪鏂囦欢鍚嶅悗闈㈡坊鍔狅紙n锛夛紱
     * @return 鐪熸琚垱寤虹殑鏂囦欢锛屾垨鑰呮槸null锛�
     */
    public File createFileSafely(File file,boolean cover){
		File parent=file.getParentFile();
        if (parent!=null&&!parent.exists()){
          boolean b=  parent.mkdirs();
            if (!b) return null;
        }

        if (!file.exists()){
            try{
            boolean b=file.createNewFile();
                if (b)return file; else return null;
            }
            catch (Throwable t){
                t.printStackTrace();
            }
        }
        else{
            if (cover){
                return file;
            }else{
                String p=file.getParent();
                String format="";
                String name=file.getName();
                if (file.isFile()){
                    int indexOfDot=name.lastIndexOf(".");
                    if (indexOfDot==-1)indexOfDot=name.length();
                    format=name.substring(indexOfDot);
                    name=name.substring(0,indexOfDot);

                }
                for (int i=1;file.exists();i++){
                    file=new File(p+"/"+name+'('+i+')'+format);
                }try {
                    boolean b=file.createNewFile();
                    if (b)return file;else return null;
                }catch (Throwable t){
                    t.printStackTrace();
                }

            }
        }
return null;
    }
    public File mkDirsSafely(File dir ,boolean cover){


        if (!dir.exists()){
            try{
                boolean b=dir.mkdirs();
                if (b)return dir; else return null;
            }
            catch (Throwable t){
                t.printStackTrace();
            }
        }
        else{
            if (cover){
                return dir;
            }else{
                String p=dir.getPath();
                for (int i=1;dir.exists();i++){
                    dir=new File(p+'('+i+')');
                }try {
                    boolean b=dir.mkdirs();
                    if (b)return dir;else return null;
                }catch (Throwable t){
                    t.printStackTrace();
                }

            }
        }
        return null;
    }

    public void write(File file,byte[] bytes){
        FileOutputStream outputStream=null;
        try
        {
            outputStream=new FileOutputStream(file);
            outputStream.write(bytes);
        }catch (Throwable t){
            t.printStackTrace();
        }finally {
            try
            {
                if (outputStream!=null){
                    outputStream.close();
                }
            }catch (Throwable t){
                t.printStackTrace();
            }
        }
    }
    public byte[] read(File file){
        FileInputStream fileInputStream=null;
        try
        {fileInputStream=new FileInputStream(file);
            byte[] buffer=new byte[1024];
            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            int count ;
            while((count=fileInputStream.read(buffer))!=-1){
            bos.write(buffer,0,count);
            }
            return  bos.toByteArray();
        }catch (Throwable t){
            t.printStackTrace();
        }finally {
            try
            {
                if (fileInputStream!=null){
                    fileInputStream.close();
                }
            }catch (Throwable t){
                t.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 鎴彇 file 鍦�鎸囧畾璺緞涓嬬殑璺緞锛屾瘮濡�file 涓�a/b/c锛宒ir涓�a锛岄偅涔堢粨鏋滃氨鏄�b/c
     * @param file 瀛愭枃浠�
     * @param dir 鐩綍
     * @return 濡傛灉dir涓棤娉曟壘鍒癴ile锛屽氨涓簄ull锛�
     */
    public String getSubPath(File file,File dir){
        String a=file.getAbsolutePath();
        String b=dir.getAbsolutePath();
        if (!a.startsWith(b))return  null;

        return a.substring(b.length());
    }
    public void copy(File file,File aimDir){
        if (!file.exists())return;
        if (file.isFile()){
            File newFile=new File(aimDir.getPath()+"/"+file.getName());
            createFileSafely(newFile,true);
            copyFile(file,newFile);
        }
        else if (file.isDirectory()){
            ArrayList<File > files=
            getAllSubFiles(file);

            for (File f:files){
                File newFile=new File(aimDir.getPath()+getSubPath(f,file));
                createFileSafely(newFile,false);
                copyFile(f,newFile);
            }

        }
    }

    /**
     * 鍙兘澶嶅埗鏂囦欢
     * @param file 婧愭枃浠�
     * @param newFile 鐩爣鏂囦欢
     */
    private void copyFile(File file, File newFile){
        FileInputStream fileInputStream=null;
        FileOutputStream fileOutputStream=null;
        try {
            fileInputStream=new FileInputStream(file);
            fileOutputStream=new FileOutputStream(newFile);
            int count;
            byte[] buffer=new byte[1024];
            while((count=fileInputStream.read(buffer))!=-1){
                fileOutputStream.write(buffer,0,count);
            }
        }catch (Throwable t){
            t.printStackTrace();
        }
        finally {
            try{
                if (fileInputStream!=null)fileInputStream.close();
                if (fileOutputStream!=null)fileOutputStream.close();
            }catch (Throwable t){
                t.printStackTrace();
            }
        }
    }

}
